import { getToken } from '@/utils/cookie'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/oj/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
    },
    {
      // 添加一个重定向
      path: '/',
      redirect: '/oj/login',
    },
    {
      path: '/oj/system',
      name: 'system',
      component: () => import('@/views/System.vue'),
      children: [
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/Cuser.vue'),
        },
        {
          path: 'question',
          name: 'question',
          component: () => import('@/views/Question.vue'),
        },
        {
          path: 'exam',
          name: 'exam',
          component: () => import('@/views/Exam.vue'),
        },
        {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('@/views/UpdateExam.vue'),
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) =>{
  //在每个请求跳转是进行一下token的判断
  //用于解决 - 1、未登录时，能够直接访问后台菜单页面
  //2、登录后，在token未过期时，用户又想进入登录页面登录
  if(getToken()){
    // has token 
    if(to.path === "/oj/login"){
      next({path: "/oj/system"})
    }else{
      next()
    }
    }else{
      if(to.path != "/oj/login"){
        next({path: "/oj/login"})
      }else{
        next()
      }
    }
  }
)

export default router
